package com.bootdo.hjh.controller;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.AlipayApiException;
import com.bootdo.common.annotation.Log;
import com.bootdo.common.utils.IPUtils;
import com.bootdo.common.utils.MD5Utils;
import com.bootdo.common.utils.PageUtils;
import com.bootdo.common.utils.QRCodeUtil;
import com.bootdo.common.utils.R;
import com.bootdo.hjh.cache.MemberCache;
import com.bootdo.hjh.cache.Node;
import com.bootdo.hjh.domain.OrderDO;
import com.bootdo.hjh.domain.WithdrawDO;
import com.bootdo.hjh.ex.BizException;
import com.bootdo.hjh.ex.ThrowUtils;
import com.bootdo.hjh.pay.AlipayService;
import com.bootdo.hjh.service.OrderService;
import com.bootdo.hjh.service.PointsService;
import com.bootdo.hjh.service.WxPayService;
import com.bootdo.hjh.vo.OrderAdminVO;
import com.bootdo.hjh.vo.WithdrawAdminVO;
import com.bootdo.shop.service.ShopOrderService;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.UserService;
import com.google.common.collect.Maps;
import com.wxpay.sdk.WXPayUtil;

/**
 * Created by qingyong on 2018/3/31.
 */
@Controller
public class OrderController {
    private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    OrderService orderService;

    @Autowired
    UserService userService;

    @Autowired
    private AlipayService alipayService;

    @Autowired
    private PointsService pointsService;

    @Autowired
    private MemberCache memberCache;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private ShopOrderService shopOrderService;

    private static Logger logger = LoggerFactory.getLogger(OrderController.class);

    @GetMapping("/order/list")
    String getorderList() {
        return "order/orderList";
    }

    @ResponseBody
    @GetMapping("/order/list/list")
    public PageUtils list(@RequestParam("limit") Integer limit,@RequestParam("offset") Integer offset,
                          @RequestParam(value = "orderNo",required = false) String orderNo,
                          @RequestParam(value = "mobile",required = false) String mobile,
                          @RequestParam(value = "receiver",required = false) String receiver,
                          @RequestParam(value = "status",required = false) Integer status) {

        List<OrderDO> bContentList = orderService.queryOrder(offset,limit,orderNo,mobile,receiver,status);
        List<OrderAdminVO> list = convert(bContentList);
        int total = orderService.countOrder(orderNo,status,mobile,receiver);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }

    private List<OrderAdminVO> convert(List<OrderDO> orderDOS){
        List<OrderAdminVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(orderDOS)) {
            for (OrderDO orderDO : orderDOS) {
                OrderAdminVO vo = new OrderAdminVO();
                vo.copyFrom(orderDO);
                Long userId = vo.getUserId();
                if(userId!=null){
                    Node node = memberCache.getNodeInCache(userId);
                    if(node!=null){
                        vo.setUsername(node.getInfo().getUsername());
                    }
                }
                list.add(vo);
            }
        }
        return list;
    }


    @GetMapping("/withdraw/list")
    String getwithdrawList() {
        return "order/withdrawList";
    }

    @ResponseBody
    @GetMapping("/withdraw/list/list")
    public PageUtils getwithdrawListlist(@RequestParam("limit") Integer limit,@RequestParam("offset") Integer offset,
                                         @RequestParam(value = "username",required = false) String username,
                                         @RequestParam(value = "status",required = false) Integer status) {
        Long userId = null;
        if(StringUtils.isNotBlank(username)){
            UserDO userDO = userService.getByUsername(username);
            if(userDO!=null){
                userId = userDO.getUserId();
            }
        }
        List<WithdrawDO> bContentList = orderService.queryWithdraw(offset,limit,status,userId);
        List<WithdrawAdminVO> list = convert1(bContentList);
        int total = orderService.countWithdraw(status,userId);
        PageUtils pageUtils = new PageUtils(list, total);
        return pageUtils;
    }

    private List<WithdrawAdminVO> convert1(List<WithdrawDO> bContentList){
        List<WithdrawAdminVO> list = new ArrayList<>();
        if (!CollectionUtils.isEmpty(bContentList)) {
            for (WithdrawDO orderDO : bContentList) {
                WithdrawAdminVO vo = new WithdrawAdminVO();
                vo.copyFrom(orderDO);
                Integer userId = vo.getUserId();
                if(userId!=null){
                    Node node = memberCache.getNodeInCache(userId.longValue());
                    if(node!=null){
                        vo.setUsername(node.getInfo().getUsername());
                    }
                }
                list.add(vo);
            }
        }
        return list;
    }



    @Log("待支付订单")
    @GetMapping("/unpaid_list")
    public String unpaidOrderList(Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Map<String,Object> recomment = Maps.newHashMap();
        Object obj = subject.getPrincipal();
        Long userId = ((UserDO)obj).getUserId();
        List<OrderDO> data = orderService.unpaidOrderList(userId);

        int total = CollectionUtils.isEmpty(data)?0:data.size();

        Map<String,Object> metadata=new HashMap<>();
        metadata.put("type",1);
        metadata.put("total",total);
        model.addAttribute("metadata",metadata);
        model.addAttribute("data",data);
        return "hjh/order";
    }

    @Log("我的订单")
    @GetMapping("/my_list")
    public String myOrderList(Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Map<String,Object> recomment = Maps.newHashMap();
        Object obj = subject.getPrincipal();
        Long userId = ((UserDO)obj).getUserId();

        List<OrderDO> data = orderService.myOrderList(userId);

        int total = CollectionUtils.isEmpty(data)?0:data.size();

        Map<String,Object> metadata=new HashMap<>();
        metadata.put("type",2);
        metadata.put("total",total);

        model.addAttribute("metadata",metadata);
        model.addAttribute("data",data);
        return "hjh/order";
    }

    @Log("会员订单")
    @GetMapping("/member_list")
    public String memberOrderList(Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Map<String,Object> recomment = Maps.newHashMap();
        Object obj = subject.getPrincipal();
        Long userId = ((UserDO)obj).getUserId();
        List<OrderDO> data = orderService.memberOrderList(userId);

        int total = CollectionUtils.isEmpty(data)?0:data.size();

        Map<String,Object> metadata=new HashMap<>();
        metadata.put("type",3);
        metadata.put("total",total);

        model.addAttribute("metadata",metadata);
        model.addAttribute("data",data);
        return "hjh/order";
    }

    @Log("发货订单")
    @GetMapping("/deliver_list")
    public String deliverOrderList(Model model){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getPrincipal();
        Long userId = ((UserDO)obj).getUserId();
        List<OrderDO> data = orderService.deliverOrderList(userId);

        int total = CollectionUtils.isEmpty(data)?0:data.size();

        Map<String,Object> metadata=new HashMap<>();
        metadata.put("type",4);
        metadata.put("total",total);

        model.addAttribute("metadata",metadata);
        model.addAttribute("data",data);
        return "hjh/order";
    }

    @Log("选择支付方式界面")
    @GetMapping("/pay")
    public String goPay(Model model,OrderDO orderDO){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        Object obj = subject.getPrincipal();
        Long userId = ((UserDO)obj).getUserId();
        if(orderDO.getId() == null) {
        		throw new RuntimeException("订单ID不能为空");
        }
        OrderDO order = orderService.getOrderById(orderDO.getId());
        if(order == null) {
        		throw new RuntimeException("订单不存在");
        }
        model.addAttribute("order", order);
        Integer cashPointsTotal = pointsService.cashPointsTotal(userId);
        String cashPointBalanceStr = "0.00";
        if(cashPointsTotal!=null){
            cashPointBalanceStr = new java.text.DecimalFormat("#.00").format(cashPointsTotal/100.0);
        }
        model.addAttribute("cashPointBalance",cashPointsTotal);
        model.addAttribute("cashPointBalanceStr",cashPointBalanceStr);
        return "hjh/pay";
    }

    @Log("订单使用现金积分支付")
    @PostMapping("/cash_pay")
    @ResponseBody
    public R cashPay(Model model,@RequestBody Map<String,String> param ){
        //获取当前用户
        R r = R.ok();
        Subject subject = SecurityUtils.getSubject();
        //{"orderId":orderId,"payPwd":payPwd};
        Integer orderId = null;
        String payPwd = null;
        try{
            payPwd = param.get("payPwd");
            Subject currentUser = SecurityUtils.getSubject();
            UserDO userDO = (UserDO)currentUser.getSession().getAttribute("user");

            ThrowUtils.throwCondition(StringUtils.isBlank(param.get("orderId")),100,"订单ID不能为空");
            ThrowUtils.throwCondition(StringUtils.isBlank(payPwd),100,"支付密码不能为空");
            //校验交易密码
            UserDO user = userService.get(userDO.getUserId());
            String currPayPwd = MD5Utils.encrypt(payPwd);
            ThrowUtils.throwCondition(user.getPayPwd() == null,100,"还未设置交易密码, 请前往个人中心设置");
            ThrowUtils.throwCondition(!user.getPayPwd().equals(currPayPwd),100,"交易密码错误");

            orderId = Integer.valueOf(param.get("orderId"));
            OrderDO orderDO = orderService.getOrderById(orderId);
            ThrowUtils.throwCondition(orderDO==null,100,"订单不存在");
            ThrowUtils.throwCondition(orderDO.getOrderStatus()!=0,100,"订单状态错误");

            //去支付
            orderService.cashPay(user,orderDO);

            if(userDO.getUserId().equals(orderDO.getUserId())){
                r.put("target","/my_list");
            }else if(userDO.getUserId().equals(orderDO.getCreateUserId())){
                r.put("target","/member_list");
            }
        }catch(BizException ex){
            r = R.error(ex.getCode(),ex.getMessage());
        }catch (Exception ex){
            LOGGER.error("现金积分支付错误",ex);
            r = R.error(101,"服务器异常");
        }
        return r;
    }

    @Log("订单--支付宝支付")
    @RequestMapping("/alipay_pay")
    @ResponseBody
    public String alipay(Model model,OrderDO orderDO){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        if(orderDO.getId() == null) {
	    		throw new RuntimeException("订单ID不能为空");
	    }
	    OrderDO order = orderService.getOrderById(orderDO.getId());
	    if(order == null) {
	    		throw new RuntimeException("订单不存在");
	    }
	    Float amount = order.getAmount() / 100f;
	    BigDecimal b = new  BigDecimal(amount);
	    Float f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        String result = alipayService.pay(order.getOrderNo(),
        		String.valueOf(f1),
        		order.getOrderTitle(),
        		order.getOrderTitle(),null);
        return "<html>".concat(result).concat("</html>");
    }


    @Log("订单--支付宝支付回调")
    @RequestMapping("/order/alipay/webhook")
    @ResponseBody
    public String alipayWebhook(HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException{
    		logger.info("支付宝回调成功");
    		//获取支付宝POST过来反馈信息
	    	Map<String,String> params = new HashMap<String,String>();
	    	Map<String,String[]> requestParams = request.getParameterMap();
	    	for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
	    		String name = (String) iter.next();
	    		String[] values = (String[]) requestParams.get(name);
	    		String valueStr = "";
	    		for (int i = 0; i < values.length; i++) {
	    			valueStr = (i == values.length - 1) ? valueStr + values[i]
	    					: valueStr + values[i] + ",";
	    		}
	    		//乱码解决，这段代码在出现乱码时使用
	    		//valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
	    		params.put(name, valueStr);
	    	}
	    	logger.info("params : {}",params);
	    //	boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
	    	//——请在这里编写您的程序（以下代码仅作参考）——
	    	/* 实际验证过程建议商户务必添加以下校验：
	    	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	    	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	    	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	    	4、验证app_id是否为该商户本身。
	    	*/
	    	//if(signVerified) {//验证成功
	    		logger.info("验证成功");
	    		//商户订单号
	    		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

	    		//支付宝交易号
	    		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

	    		//交易状态
	    		String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

	    		if(trade_status.equals("TRADE_FINISHED")){
	    			logger.info("TRADE_FINISHED");
	    			//判断该笔订单是否在商户网站中已经做过处理
	    			//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	    			//如果有做过处理，不执行商户的业务程序

	    			//注意：
	    			//退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
	    		}else if (trade_status.equals("TRADE_SUCCESS")){
	    			logger.info("TRADE_SUCCESS");
	    			//判断该笔订单是否在商户网站中已经做过处理
	    			//如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
	    			//如果有做过处理，不执行商户的业务程序
	    			//标记订单为已支付
	    			if(out_trade_no.startsWith("A")) {
	    			    // 商城订单
	    				shopOrderService.paySuccessCallback(out_trade_no,"支付宝支付", null, trade_no);

	    			}else {
	    			    // 会员订单
	    				orderService.updateOrderToPaid(out_trade_no,"支付宝支付");
	    			}
	    			//注意：
	    			//付款完成后，支付宝系统发送该交易状态通知
	    		}
	    		logger.info("支付宝回调--success");
	    		return "success";
	    //	}else {//验证失败
	    		//logger.info("支付宝回调--fail");
	    		//return "fail";
	    		//调试用，写文本函数记录程序运行情况是否正常
	    		//String sWord = AlipaySignature.getSignCheckContentV1(params);
	    		//AlipayConfig.logResult(sWord);
	    	//}
    }

    //@Log("订单--支付宝支付--回调页面")
    @RequestMapping("/order/alipay_return")
    public String alipayReturn(Model model,OrderDO orderDO){
        //获取当前用户

    		return "redirect:/";
    }

    @Log("订单--微信支付发起支付请求")
    @RequestMapping("/wx_pay")
    public String wxPayUnifiedOrder(HttpServletRequest request,Model model,OrderDO orderDO) throws Exception{
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        if(orderDO.getId() == null) {
	    		throw new RuntimeException("订单ID不能为空");
	    }
	    OrderDO order = orderService.getOrderById(orderDO.getId());
	    if(order == null) {
	    		throw new RuntimeException("订单不存在");
	    }
	    model.addAttribute("order", order);

	    Map<String, String> r = wxPayService.doPay(order.getOrderTitle(), order.getOrderNo(), order.getAmount().toString(), IPUtils.getIpAddr(request), order.getProductId().toString());
        String path = "";
        try {
            if(null != r.get("err_code") && r.get("err_code").toString().equals("INVALID_REQUEST")) {
            		/**如果订单号已重复，更新订单号，再重新生成**/
            		//更新订单号
            		orderService.updateOrderNo(orderDO.getId());
            		order = orderService.getOrderById(orderDO.getId());
                r = wxPayService.doPay(order.getOrderTitle(), order.getOrderNo(), order.getAmount().toString(), IPUtils.getIpAddr(request), order.getProductId().toString());
            }
            if(null != r.get("err_code") && r.get("err_code").toString().equals("ORDERPAID")) {
	        		/**订单已支付**/
            		model.addAttribute("msg", "该订单已支付");
	        }
            String codeUrl = r.get("code_url").toString();
            String destPath = "/mnt/hjh/wx/qrcode/";
            path = QRCodeUtil.encode(codeUrl, destPath);
            model.addAttribute("path", "wx/qrcode/"+path);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "hjh/wx_pay";
    }

    @Log("订单--微信支付回调")
    @RequestMapping("/order/wx/webhook")
    @ResponseBody
    public String wxWebhook(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String result;//返回给微信的处理结果
        String inputLine;
        String notityXml = "";
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        //微信给返回的东西
        try {
            while ((inputLine = request.getReader().readLine()) != null) {
                notityXml += inputLine;
            }
            request.getReader().close();
        } catch (Exception e) {
            e.printStackTrace();
            logger.info("xml获取失败");
            result = setXml("fail","xml获取失败");
            return result;
        }
        if (StringUtils.isEmpty(notityXml)) {
        		logger.info("xml为空");
            result = setXml("fail","xml为空");
            return result;
        }
        logger.info("notityXml : {}",notityXml);
        Map<String,String> map = WXPayUtil.xmlToMap(notityXml);
        logger.info("map : {}",map);
//        WXPay wxPay = new WXPay(WXConfig.getInstance());
//        boolean valid = wxPay.isPayResultNotifySignatureValid(map);
//        if(!valid) {
//        		logger.info("签名验证失败");
//        		result = setXml("fail","签名验证失败");
//        		return result;
//        }
        String out_trade_no = (String) map.get("out_trade_no");// 获取商户订单号
        if(out_trade_no.startsWith("A")) {
			shopOrderService.paySuccessCallback(out_trade_no,"微信支付", null, null);
		}else {
			OrderDO orderDO = orderService.getOrderByNo(out_trade_no);
	        if(orderDO == null) {
		        	result = setXml("fail","订单不存在");
		    		return result;
	        }
	        orderService.updateOrderToPaid(out_trade_no,"微信支付");
		}
        /**
        String appid = (String) map.get("appid");//应用ID
        String attach = (String) map.get("attach");//商家数据包
        String bank_type = (String) map.get("bank_type");//付款银行
        String cash_fee = (String) map.get("cash_fee");//现金支付金额
        String fee_type = (String) map.get("fee_type");//货币种类
        String is_subscribe = (String) map.get("is_subscribe");//是否关注公众账号
        String mch_id = (String) map.get("mch_id");//商户号
        String nonce_str = (String) map.get("nonce_str");//随机字符串
        String openid = (String) map.get("openid");//用户标识
//        String out_trade_no = (String) map.get("out_trade_no");// 获取商户订单号
        String result_code = (String) map.get("result_code");// 业务结果
        String return_code = (String) map.get("return_code");// SUCCESS/FAIL
        String sign = (String) map.get("sign");// 获取签名
        String time_end = (String) map.get("time_end");//支付完成时间
        String total_fee = (String) map.get("total_fee");// 获取订单金额
        String trade_type = (String) map.get("trade_type");//交易类型
        String transaction_id = (String) map.get("transaction_id");//微信支付订单号

        SortedMap<String, String> parameters = new TreeMap<String, String>();
        // 数据加密
        parameters.put("appid", appid);//应用ID
        parameters.put("attach", attach);//商家数据包
        parameters.put("bank_type", bank_type);//付款银行
        parameters.put("cash_fee", cash_fee);//现金支付金额
        parameters.put("fee_type", fee_type);//货币种类
        parameters.put("is_subscribe", is_subscribe);//是否关注公众账号
        parameters.put("mch_id", mch_id);//商户号
        parameters.put("nonce_str", nonce_str);//随机字符串
        parameters.put("openid", openid);//用户标识
        parameters.put("out_trade_no", out_trade_no);// 商户订单号
        parameters.put("result_code", result_code);// 业务结果
        parameters.put("return_code", return_code);// SUCCESS/FAIL
        parameters.put("time_end", time_end);// 支付完成时间
        parameters.put("total_fee", total_fee);// 获取订单金额
        parameters.put("trade_type", trade_type);//交易类型
        parameters.put("transaction_id", trade_type);//微信支付订单号
        //加密前验证notify支付订单网关---https://gw.tenpay.com/gateway/simpleverifynotifyid.xml
//        RequestHandler reqHandler = new RequestHandler(request, response);
//        reqHandler.init(appid, appsecret, partnerkey);
//        //MD5加密
//        String endsign = reqHandler.createSign(parameters);
        System.out.println("**************************************************************************************************");
        System.out.println(appid+"-------------------应用ID");
        System.out.println(attach+"-------------------商家数据包");
        System.out.println(bank_type+"-------------------付款银行");
        System.out.println(cash_fee+"-------------------现金支付金额");
        System.out.println(fee_type+"-------------------货币种类");
        System.out.println(is_subscribe+"-------------------是否关注公众账号");
        System.out.println(mch_id+"-------------------商户号");
        System.out.println(nonce_str+"-------------------随机字符串");
        System.out.println(openid+"-------------------用户标识");
        System.out.println(out_trade_no+"-------------------获取商户订单号");
        System.out.println(result_code+"-------------------业务结果");
        System.out.println(return_code+"------------------- SUCCESS/FAIL");
        System.out.println(sign+"-------------------获取签名-微信回调的签名");
        System.out.println(time_end+"-------------------支付完成时间");
        System.out.println(total_fee+"-------------------获取订单金额");
        System.out.println(trade_type+"-------------------交易类型");
        System.out.println(transaction_id+"-------------------微信支付订单号");
//      System.out.println(endsign+"-------------------第二次加密sign");
 		System.out.println("**************************************************************************************************");
		*
		*/
        // 验证签名
        result = setXml("SUCCESS", "OK");
        /**
        if (sign.equals(endsign)) {
            result = setXml("SUCCESS", "OK");
        } else {
            System.err.println("签名不一致！");
            result = setXml("fail", "签名不一致！");
        }
        if (!"SUCCESS".equals("SUCCESS")) {
            System.err.println("微信返回的交易状态不正确（result_code=" + "SUCCESS" + "）");
            result =  setXml("fail", "微信返回的交易状态不正确（result_code=" + "SUCCESS" + "）");
        }
        **/
//        logger.info("result : {}",result);
        return result;
    }


  //通过xml 发给微信消息
    public static String setXml(String return_code, String return_msg) {
        SortedMap<String, String> parameters = new TreeMap<String, String>();
        parameters.put("return_code", return_code);
        parameters.put("return_msg", return_msg);
        return "<xml><return_code><![CDATA[" + return_code + "]]>" +
                "</return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
    }

    /**
     * 修改订单
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/order/modify_status")
    public R modifyOrderStatus(@RequestBody Map<String,String> param){
        Integer orderId = Integer.valueOf(param.get("id"));
        Integer status =Integer.valueOf(param.get("status"));
        orderService.updateStatus(orderId,status);
        return R.ok();
    }

    /**
     * 修改提现状态
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST,value = "/withdraw/modify_status")
    public R modifyWithdrawStatus(@RequestBody Map<String,String> param){
        Integer orderId = Integer.valueOf(param.get("id"));
        Integer status =Integer.valueOf(param.get("status"));
        orderService.updateWithdrawStatus(orderId,status);
        return R.ok();
    }

    /**
     * 修改提现状态
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET,value = "/order/deliver/{orderId}")
    public R deliver(@PathVariable("orderId") Integer orderId){
        pointsService.deliver(orderId);
        return R.ok();
    }


}
